package com.dhy.socket.request.core;

import com.dhy.socket.request.util.RawRequestParse;
import com.dhy.socket.request.util.RequestKey;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 大忽悠
 * @create 2022/6/20 17:25
 */
@Slf4j
public class HttpRequestInHandler extends ChannelInboundHandlerAdapter {
    private static final ThreadLocal<DhyHttpRequest> REQ = new ThreadLocal<>();
    private static final ThreadLocal<DefaultFullHttpResponse> RES = new ThreadLocal<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //解析请求行，请求头
        if (msg instanceof HttpRequest) {
            REQ.set(RawRequestParse.parseHttpRequest((HttpRequest) msg));
            RES.set(new DefaultFullHttpResponse(((HttpRequest) msg).protocolVersion(),HttpResponseStatus.OK));
        }
        //解析请求体
        else if (msg instanceof HttpContent) {
            DhyHttpRequest dhyHttpRequest = REQ.get();
            RawRequestParse.parseHttpContent(dhyHttpRequest, (HttpContent) msg);
            //通过RequestDispatcher,寻找当前请求应该交给哪个controller处理
            RequestDispatcher.handle(new RequestKey(dhyHttpRequest.getMethod(), dhyHttpRequest.getUrl(),dhyHttpRequest,RES.get()));
            ctx.writeAndFlush(RES.get());
        }
    }
}
